﻿using UnityEngine;
using System.Collections;

public class ObjectSpawner : MessageScript {

	public float SpawnFrequency { get; set; }
	public GameObject objectPreFab { get; set; }
	public GameObject[] multipleObjectPreFabs { get; set; }
	public float ObjectSpawnFrequency { get; set; }
	public float timer;
	public Transform ParentObject = null;
	Vector2 objectSize = Vector2.zero;
	// Use this for initialization
	public void Start () {

	}
	public void SetUp(float spawnFrequency, GameObject preFab, Transform parentTransform)
	{
		ObjectSpawnFrequency = spawnFrequency;
		this.objectPreFab = preFab;
		this.ParentObject = parentTransform;
		objectSize.x = preFab.GetComponent<SpriteRenderer> ().renderer.bounds.size.x * 20;
		objectSize.y = preFab.GetComponent<SpriteRenderer> ().renderer.bounds.size.y * 20;
	}
	public void SetUp(float spawnFrequency, GameObject[] preFab, Transform parentTransform)
	{
		ObjectSpawnFrequency = spawnFrequency;
		this.multipleObjectPreFabs = preFab;
		this.ParentObject = parentTransform;
		objectSize.x = preFab[0].GetComponent<SpriteRenderer> ().renderer.bounds.size.x * 20;
		objectSize.y = preFab[0].GetComponent<SpriteRenderer> ().renderer.bounds.size.y * 20;
	}
	public void Spawner()
	{
		timer += Time.deltaTime;
		if (timer > ObjectSpawnFrequency) {
			timer = 0.0f;
			SpawnObject ();
		}
	}
	/// <summary>
	/// Run at Objectspawner at the location
	/// </summary>
	/// <param name="pos">Position to spawn object at.</param>
	public bool SpawnerAtPos(Vector3 pos)
	{
		timer += Time.deltaTime;
		if (timer > ObjectSpawnFrequency) {
			timer = 0.0f;
			SpawnObjectAt(pos,Quaternion.identity);
			return true;
		}
		return false;
		
	}
	public Vector3 getRandomPositionOnScreen()
	{

		float xpos = Random.Range (0 + objectSize.x, Camera.main.pixelWidth - objectSize.x);
		float ypos = Random.Range (0 + objectSize.y, Camera.main.pixelHeight - objectSize.y);
		Vector3 pos = Camera.main.ScreenToWorldPoint(new Vector3(xpos,ypos,0));
		                                                        
		pos.z = 0.0f;
		return pos;
	}
	public GameObject SpawnObject()
	{
		GameObject obj =  (GameObject)Instantiate (objectPreFab);
		obj.transform.parent = ParentObject;
		return obj;
	}
	public GameObject SpawnObjectAt(Vector3 position, Quaternion rot)
	{
		GameObject obj =  (GameObject)Instantiate (objectPreFab, position, rot);
		obj.transform.parent = ParentObject;
		return obj;
	}

}
